/**
 * 页面数据缓存存储工具
 */
import {defineStore} from 'pinia'
import {getAllCategoryJson, getAllUserJson} from "@/core/api/service";
import {copyObj} from "@/core/common/ObjectUtil";

/**
 * 本地持久化存储
 */
const LOCAL_STORE = window.localStorage;

const STORE_KEY_CURRENT_USER_ID = "SILLY_ADMIN_CURRENT_USER_ID";
const STORE_KEY_CURRENT_USER_NAME = "SILLY_ADMIN_CURRENT_USER_NAME";

const STORE_KEY_CURRENT_CATEGORY_KEY = "SILLY_ADMIN_CURRENT_CATEGORY_KEY";
const STORE_KEY_CURRENT_CATEGORY_JSON = "SILLY_ADMIN_CURRENT_CATEGORY_JSON";


const STORE_KEY_USER_OPTION_ACTIVE_MENU_KEY = "SILLY_ADMIN_USER_OPTION_ACTIVE_MENU_KEY";
const STORE_KEY_USER_OPTION_SHOW_SEARCH_FORM = "SILLY_ADMIN_USER_OPTION_SHOW_SEARCH_FORM";
const STORE_KEY_USER_OPTION_SELECT_BPMN_TYPE = "SILLY_ADMIN_USER_OPTION_SELECT_BPMN_TYPE";
const STORE_KEY_USER_OPTION_DRAW_BPMN_XML = "SILLY_ADMIN_USER_OPTION_DRAW_BPMN_XML";
const STORE_KEY_USER_OPTION_BUSINESS_JSON = "SILLY_ADMIN_USER_OPTION_BUSINESS_JSON";

export {
    LOCAL_STORE,
    STORE_KEY_CURRENT_USER_ID,
    STORE_KEY_CURRENT_USER_NAME,
    STORE_KEY_CURRENT_CATEGORY_KEY,
    STORE_KEY_CURRENT_CATEGORY_JSON,
    STORE_KEY_USER_OPTION_ACTIVE_MENU_KEY,
    STORE_KEY_USER_OPTION_SHOW_SEARCH_FORM,
    STORE_KEY_USER_OPTION_SELECT_BPMN_TYPE,
    STORE_KEY_USER_OPTION_DRAW_BPMN_XML,
    STORE_KEY_USER_OPTION_BUSINESS_JSON
};
/**
 * 用户信息存储库
 */
export const useUserStore = defineStore('user', {
    state: () => {
        const pme = getAllUserJson();
        pme.then(data => {
            const userArr = JSON.parse(data);
            let userId: string = useUserStore().userId;
            if (!userId) {
                userId = userArr.length > 0 ? userArr[0].id : '';
            }
            const userMap = new Map<string, string>();
            for (let index = 0; index < userArr.length; index++) {
                const element = userArr[index];
                element['value'] = element['id'];
                element['label'] = element['name'];
                userMap.set(element['id'], element['name']);
            }
            const userName = userMap.get(userId) || '/';
            useUserStore().$patch({userId, userName, userArr, userMap});
        });
        const userId = LOCAL_STORE.getItem(STORE_KEY_CURRENT_USER_ID) || '';
        const userName = LOCAL_STORE.getItem(STORE_KEY_CURRENT_USER_NAME) || '/';
        return {
            userId: userId,
            userName: userName,
            userArr: [{id: userId, name: userName, value: userId}],
            userMap: new Map<string, string>()
        }
    },
    actions: {
        setUserId(userId: string): void {
            this.userId = userId;
            LOCAL_STORE.setItem(STORE_KEY_CURRENT_USER_ID, userId);
            const userName = this.userMap.get(userId) || '/';
            this.userName = userName;
            LOCAL_STORE.setItem(STORE_KEY_CURRENT_USER_NAME, userName);
        },
    },
});

/**
 * 业务配置信息存储库
 */
export const useCategoryStore = defineStore('category', {
    state: () => {
        const pme = getAllCategoryJson();
        pme.then(data => {
            const categoryArr = JSON.parse(data);
            const categoryMap = new Map<string, object>();
            let active: string = useCategoryStore().active;
            for (let index = 0; index < categoryArr.length; index++) {
                const element = categoryArr[index];
                categoryMap.set(element['category'], element);
                if (!active) {
                    active = element['category'];
                }
            }
            useCategoryStore().$patch({categoryArr, categoryMap, active});
        });
        const active: string = LOCAL_STORE.getItem(STORE_KEY_CURRENT_CATEGORY_KEY) || '';
        return {categoryArr: [], categoryMap: new Map<string, object>(), active}
    },
    actions: {
        setActive(active: string) {
            LOCAL_STORE.setItem(STORE_KEY_CURRENT_CATEGORY_KEY, active);
            const data = this.categoryMap.get(active);
            if (data) {
                LOCAL_STORE.setItem(STORE_KEY_CURRENT_CATEGORY_JSON, JSON.stringify(data));
            }
            this.active = active;
        },
        activeCategory() {
            const jsonData: string = LOCAL_STORE.getItem(STORE_KEY_CURRENT_CATEGORY_JSON) || '{}';
            return JSON.parse(jsonData);
        },
        getCategory(key: string) {
            if (key === LOCAL_STORE.getItem(STORE_KEY_CURRENT_CATEGORY_KEY)) {
                const jsonData: string = LOCAL_STORE.getItem(STORE_KEY_CURRENT_CATEGORY_JSON) || '';
                if (jsonData) {
                    return JSON.parse(jsonData);
                }
            }
            return copyObj(this.categoryMap.get(key));
        }
    },
});

/**
 * 用户个性化信息存储库
 */
export const useUserOptionStore = defineStore('userOption', {
    state: () => {
        const activeMenuKey = LOCAL_STORE.getItem(STORE_KEY_USER_OPTION_ACTIVE_MENU_KEY) || "1";
        const showSearchForm = JSON.parse(LOCAL_STORE.getItem(STORE_KEY_USER_OPTION_SHOW_SEARCH_FORM) || "true");
        const selectBpmnType = LOCAL_STORE.getItem(STORE_KEY_USER_OPTION_SELECT_BPMN_TYPE) || "";
        const drawBpmnXml = LOCAL_STORE.getItem(STORE_KEY_USER_OPTION_DRAW_BPMN_XML) || "";
        const businessJsonData = JSON.parse(LOCAL_STORE.getItem(STORE_KEY_USER_OPTION_BUSINESS_JSON) ||
            `{
              "category": "demo_category",
              "processDesc": "模板测试",
              "lastProcessKey": "demo_v1",
              "master": {
                "demo_v1": {
                  "firstNodeKey": "T0010",
                  "processVersion": "v1",
                  "node": {
                    "T0010": {
                      "nodeName": "编辑",
                      "option": {},
                      "variable": {
                        "name": {
                          "desc": "姓名"
                        },
                        "age": {
                          "desc": "年龄"
                        },
                        "auditUserId": {
                          "desc": "审核人ID"
                        }
                      }
                    },
                    "T0020": {
                      "nodeName": "审核",
                      "option": {},
                      "variable": {
                        "auditOpinion": {
                          "desc": "审核意见"
                        }
                      }
                    }
                  }
                }
              },
              "searchConfig": {}
            }`);
        return {activeMenuKey, showSearchForm, selectBpmnType, drawBpmnXml, businessJsonData}
    },
    actions: {
        setActiveMenuKey(key: string) {
            LOCAL_STORE.setItem(STORE_KEY_USER_OPTION_ACTIVE_MENU_KEY, key);
            this.activeMenuKey = key;
        },
        setShowSearchForm(flag: boolean) {
            LOCAL_STORE.setItem(STORE_KEY_USER_OPTION_SHOW_SEARCH_FORM, "" + flag);
            this.showSearchForm = flag;
        },
        setSelectBpmnType(type: string) {
            LOCAL_STORE.setItem(STORE_KEY_USER_OPTION_SELECT_BPMN_TYPE, type);
            this.selectBpmnType = type;
        },
        setDrawBpmnXml(xml: string) {
            LOCAL_STORE.setItem(STORE_KEY_USER_OPTION_DRAW_BPMN_XML, xml);
            this.drawBpmnXml = xml;
        },
        setBusinessJsonData(jsonData: object) {
            LOCAL_STORE.setItem(STORE_KEY_USER_OPTION_BUSINESS_JSON, JSON.stringify(jsonData));
            this.businessJsonData = jsonData;
        }
    },
});